package com.abel.cloud.provider.controller;

import com.abel.cloud.common.po.UserAccountPO;
import com.abel.cloud.common.response.BusinessException;
import com.abel.cloud.common.response.Resp;
import com.abel.cloud.common.response.RespCode;
import com.abel.cloud.provider.service.UserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@Slf4j
@RefreshScope
@RestController
public class IndexController {
    @Autowired
    private UserAccountService userAccountService;

    @Value("${server.port}")
    private String serverPort;
    @Value("${config.info}")
    private String configInfo;


    @GetMapping("user/{id}")
    public Resp<UserAccountPO> getUser(@PathVariable Integer id){
        log.info("=== getUser:{}", id);
        UserAccountPO user = userAccountService.getUserById(id);

        if(user == null){
            throw new BusinessException("user is not exists");
        }

        return Resp.make(RespCode.Default.SUCCESS, "port:" + serverPort, user);
    }

    @PostMapping("user/update")
    public Resp userUpdate(@RequestBody UserAccountPO user){
        log.info("=== updateUser:{}", user.getId());
        int result = userAccountService.updateUserAccount(user);

        return Resp.ok(result);
    }

    /**
     * @date 2021/5/13 11:44
     * @author Abel.lin
     * @description 负载测试
     * @return
     */
    @GetMapping("lb")
    public Resp lb(){
        log.info("=== lb:{}", serverPort);
        return Resp.ok(serverPort);
    }

    /**
     * @date 2021/5/10 14:39
     * @author Abel.lin
     * @description 模拟请求超时
     * @param sec 秒数
     * @return
     */
    @GetMapping("timeout/{sec}")
    public Resp timeOut(@PathVariable int sec){
        log.info("=== timeOut:{}", sec);
        try {
            TimeUnit.SECONDS.sleep(sec);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Resp.ok("yes");
    }

    /**
     * @date 2021/5/13 18:12
     * @author Abel.lin
     * @description 获取配置中心信息
     * @return
     */
    @GetMapping("config")
    public Resp config(){
        log.info("=== config:{}", configInfo);
        return Resp.ok(configInfo);
    }


}
